import aiohttp
from selectolax.parser import HTMLParser

from weed_shop.core.models.enums.currency import Currency


async def get_currency_rate(currency_to: Currency) -> float | None:
    """Получаем курс валют c биржи okx"""

    headers = {
        "accept": "application/json",
        "accept-language": "en-GB,en-US;q=0.9,en;q=0.8",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.5842.194 Safari/537.36",
        "x-locale": "ru_RU",
    }

    params = None
    if currency_to == Currency.ton:
        url = "https://www.okx.com/ru/convert/ton-to-thb"
    else:
        params = {
            "t": "1697541923463",
            "cryptoCurrency": currency_to.value.upper(),
            "fiatCurrency": "THB",
            "side": "sell",
        }
        url = "https://www.okx.com/v3/c2c/tradingOrders/mostUsedPaymentAndBestPriceAds"

    async with aiohttp.ClientSession() as session, session.get(url, params=params, headers=headers) as response:
        if response.status != 200:
            return None

        if currency_to == Currency.ton:
            tree = HTMLParser(await response.text())
            try:
                rate = tree.css_first("h2").text()
                rate = rate.replace("฿", "").replace(",", ".").strip()
                return float(rate)
            except (AttributeError, ValueError):
                return None
        else:
            try:
                content = await response.json()
            except aiohttp.ContentTypeError:
                return None

            offers = content.get("data", [])
            if not offers:
                return None
            best_offer = next((offer for offer in offers if offer.get("bestOption")), offers[0])

            return float(best_offer["unitPrice"])
